<?php

namespace app\purchase\controller;

use app\purchase\model\Client;
use think\Request;
use think\Exception;
use app\purchase\model\User as UserModel;

class User extends \PurchaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $userModel = new UserModel();

        try {
            $data = $userModel->where([
                'status' => 1,
            ])->order('user_id')
                ->field('user_id,user_name,mobile,email,qq,create_at')
                ->select();

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $userModel = new UserModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $userModel = new UserModel();

        $data = $request->post();

        /* @var $validate \ShopValidate */
        $validate = \think\Loader::validate('User');
        if ( !$validate->scene('save')->check($data) ) {
            return $validate->getError();
        }

        try {
            $data['salt'] = $userModel->generateSalt();
            $data['password'] = md5($data['password'] . $data['salt']);

            $result = $userModel->data($data)->allowField(true)->save();

            if (! $result) {
                $this->serverErrorTerminate('资源新增失败');
            }
            unset($userModel->password);
            unset($userModel->salt);

            $this->successTerminate($userModel);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $userModel = new UserModel();

        try {
            $data = $userModel->get($id);
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $userModel = new UserModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $userModel = new UserModel();
        $data = $request->post();

        $pk = $userModel->getPk();
        if ( isset($data[$pk]) ) unset($data[$pk]);

        try {
            $result = $userModel->allowField(true)->save($data, [
                $pk => $id,
            ]);
            if (! $result) $this->serverErrorTerminate('更新资源失败');
            $this->successTerminate($userModel);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $userModel = new UserModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }



    /**
     * 登录
     */
    public function login($username, $password)
    {
        try {

            $StaffModel = new \app\crm\model\Staff();
            $ClientStaff = new \app\shop\model\ClientStaff();

            empty($username)&&\exception('登录账号不能为空');

            $user = $StaffModel->field('staff_id,staff_name,password,salt,phone,is_downstream')
                ->where('user_name', $username)
                ->whereOr('staff_name',$username)
                ->whereOr('phone',$username)
                ->find();

            if(empty($user) || $user['is_downstream'] === 1){
                \exception('登录账号不存在');
            }

            $company_list = $ClientStaff->alias('a')
            ->join('sh_client b','a.client_id = b.client_id')
            ->where('a.staff_id',$user['staff_id'])
            ->where('a.is_orderer',1)
            ->field('b.client_id,b.client_name')
            ->select();

            if(empty($company_list)){
                \exception('无权登录');
            }

            $passwordUser = md5($password . $user->salt);
            $passwordUser === $user->password || \exception('密码错误');
            // 登录成功
            // 生成token & 更新最后登录时间
            $TOKEN  = $this->generateToken();
            $data = [
                'last_login' => time(),
                'token' => $TOKEN,
            ];
            $StaffModel->save($data, [
                'staff_id' => $user->staff_id,
            ]);

            $user->setAttr('company_list',$company_list);
            $user->setAttr('company',$company_list[0]['client_id']);
            $user->setAttr('token', $data['token']);
            unset($user->password);
            unset($user->salt);
            unset($user->is_downstream);

            $this->successTerminate($user);

        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }

    }



    protected function noVerifyToken()
    {
        return ['login', 'save'];
    }


    public function change_company(Request $request){

        try{

            $params = $request->post();

            $ClientStaff = new \app\shop\model\ClientStaff();

            $flag = $ClientStaff->where('client_id',$params['company'])->where('staff_id',$params['staff_id'])->find();

            if(empty($flag) || $flag['is_orderer'] !== 1){
                $this->successTerminate(false);
            }else{
                $this->successTerminate(true);
            }

        }catch(Exception $e){

            $this->serverErrorTerminate($e->getMessage());

        }

    }

}
